import { Button, Card, Empty, message, Space, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { listDataSourceByPage } from '@/services/dataSourceService';
import DataSourceCard from './DataSourceCard';
import { DEFAULT_PAGE_SIZE } from '@/constants';
import { useModel } from '@umijs/max';

/**
 * 数据源列表组件
 * @constructor
 */
const DataSourceList: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [dataSourceList, setDataSourceList] = useState<DataSourceType.DataSource[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const { initialState } = useModel('@@initialState');

  const loadData = async (page = 1, pageSize = DEFAULT_PAGE_SIZE) => {
    setLoading(true);
    try {
      const res = await listDataSourceByPage({
        page,
        pageSize,
      });
      setDataSourceList(res.data.records);
      setTotal(res.data.total);
      setCurrentPage(page);
    } catch (e: any) {
      message.error('加载数据源失败，' + e.message);
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <div>
      <Spin spinning={loading}>
        {dataSourceList.length > 0 ? (
          <Space direction="vertical" size={16}>
            {dataSourceList.map((dataSource) => (
              <DataSourceCard
                key={dataSource.id}
                dataSource={dataSource}
                actions={[
                  <Button type="primary" key="edit">
                    编辑
                  </Button>,
                  <Button danger key="delete">
                    删除
                  </Button>,
                ]}
              />
            ))}
          </Space>
        ) : (
          <Card>
            <Empty description="暂无数据源" />
          </Card>
        )}
      </Spin>
    </div>
  );
};

export default DataSourceList;
